package com.linwl.weatherforecast.service;


import com.linwl.weatherforecast.utils.YamlReader;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @className: WeChatService
 * @author: linwl
 * @desc:
 * @date: 2023/10/12
 **/
@Slf4j
public class WeChatService {

    private WeChatService() {

    }

    /**
     * server酱发送
     *
     * @param title 标题
     * @param text  内容
     */
    public static void send(String title, String text, String key) {
        log.info("开始发送server酱微信消息!");
        try {
            String url = YamlReader.getInstance().getValueByPath("server.wechat.url") + key + ".send";
            String postData = "text=" + URLEncoder.encode(title, "UTF-8") + "&desp=" + URLEncoder.encode(text, "UTF-8");
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(postData);
            wr.flush();
            wr.close();
            int responseCode = con.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } catch (Exception e) {
            log.error("开始发送server酱微信消息异常:",e);
        }
    }

}
